/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.mzk.oai.metadataRepository.harvest.tei.svnManager;

import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.auth.ISVNAuthenticationManager;
import org.tmatesoft.svn.core.internal.io.dav.DAVRepositoryFactory;
import org.tmatesoft.svn.core.internal.io.svn.SVNRepositoryFactoryImpl;
import org.tmatesoft.svn.core.io.SVNRepository;
import org.tmatesoft.svn.core.io.SVNRepositoryFactory;
import org.tmatesoft.svn.core.wc.SVNWCUtil;

/**
 *
 * @author Martin Řehánek (rehan at mzk.cz)
 */
public class RepositoryFactory {

    public static SVNRepository getRepository(String url) throws SVNException {
        if (url.startsWith("http://")) {
            return byHttpProtocol(url);
        } else if (url.startsWith("svn://")) {
            return bySvnProtocol(url);
        } else {
            throw new IllegalArgumentException("Wrong url");
        }
    }

    public static SVNRepository getRepository(String url, String name, String password) throws SVNException {
        if (url.startsWith("http://")) {
            return byHttpProtocol(url, name, password);
        } else if (url.startsWith("svn://")) {
            return bySvnProtocol(url, name, password);
        } else {
            throw new IllegalArgumentException("Wrong url");
        }
    }

    private static SVNRepository byHttpProtocol(String url) throws SVNException {
        initHttp();
        return withoutAuthentication(url);
    }

    private static void initHttp() {
        DAVRepositoryFactory.setup();
    }

    private static SVNRepository withoutAuthentication(String url) throws SVNException {
        return SVNRepositoryFactory.create(SVNURL.parseURIDecoded(url));
    }

    private static SVNRepository bySvnProtocol(String url) throws SVNException {
        initSvn();
        return withoutAuthentication(url);
    }

    private static void initSvn() {
        SVNRepositoryFactoryImpl.setup();
    }

    private static SVNRepository byHttpProtocol(String url, String name, String password) throws SVNException {
        initHttp();
        return withAuthentication(url, name, password);
    }

    private static SVNRepository withAuthentication(String url, String name, String password) throws SVNException {
        SVNRepository repository = RepositoryFactory.getRepository(url);
        ISVNAuthenticationManager authManager = SVNWCUtil.createDefaultAuthenticationManager(name, password);
        repository.setAuthenticationManager(authManager);
        return repository;
    }

    private static SVNRepository bySvnProtocol(String url, String name, String password) throws SVNException {
        initSvn();
        return withAuthentication(url, name, password);
    }
}
